<?php

class AdPhotosController extends AppController {

  //public $scaffold;
  public $helpers = array('Html', 'TWSForm', 'Paginator');
  public $components = array('Session', 'Util', 'Upload');
  public $name = 'AdPhotos';
  public $paginate;

  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
        'limit' => Configure::read('App.pageResultLimit'),
        'order' => array(
            'AdPhoto.created' => 'desc'
            ));
  }

//admin and public version
  function admin_index($adId=null) {
    $this->layout = "admin";
    $adGroupInfo = $this->AdPhoto->Ad->find('first', $this->_getOptions($adId));
    if (empty($adId) || empty($adGroupInfo)) {
      $this->render('admin_invalid');
    }
    $this->set(array('adId' => $adId, 'groupInfo' => $adGroupInfo));
    //http://book.cakephp.org/view/1232/Controller-Setup -- Here is where you can pass in special conditions
    $this->set('photos', $this->paginate('AdPhoto',
                    array('AdPhoto.ad_id' => $adId)));
  }

  function admin_add($adId) {
    $this->layout = 'admin';
    $adGroupInfo = $this->AdPhoto->Ad->find('first', $this->_getOptions($adId));
    if (empty($adId) || empty($adGroupInfo)) {
      $this->render('admin_invalid');
    }
    $this->set(array('adId' => $adId, 'groupInfo' => $adGroupInfo));
    if ($this->request->is('post')) {
      $this->_processAction($this->request, 'add');
    }
  }

  function admin_add_multiple($adId=null) {
    $this->layout = 'admin';
    $adGroupInfo = $this->AdPhoto->Ad->find('first', $this->_getOptions($adId));
    if (empty($adId) || empty($adGroupInfo)) {
      $this->render('admin_invalid');
    }
    $this->set(array('adId' => $adId, 'groupInfo' => $adGroupInfo));
    if ($this->request->is('post')) {
      $this->render('admin_invalid'); //handled in ImagesController
    }
  }

  //admin
  function admin_edit($adPhotoId = null, $adId = null) {
    $this->layout = 'admin';
    $adGroupInfo = $this->AdPhoto->Ad->find('first', $this->_getOptions($adId));
    if (empty($adPhotoId) || empty($adId) || empty($adGroupInfo)) {
      $this->render('admin_invalid');
    }
    $this->set(array('adId' => $adId, 'groupInfo' => $adGroupInfo));
    //TODO - options have to be changed. We have the photo id here not the album id, the link  and possible category/album data will be incorrect
    $this->AdPhoto->id = $adPhotoId;
    if ($this->request->is('get')) {
      $this->request->data = $this->AdPhoto->read();
    } else {
      //check for delete announcement
      if (isset($this->request->data['deleteBtn'])) {
        $this->admin_delete($adPhotoId, $adId);
      } else {
        $this->_processAction($this->request, 'edit', $adPhotoId);
      }
    }
  }

  function admin_edit_ajax($id = null) {
    $this->layout = 'admin';
    $result = array();
    if ($this->request->is('post')) {
      $data = $this->request->data;
      $this->AdPhoto->id = $data['adPhotoId'];
      $updateResult = $this->AdPhoto->save(array("AdPhoto" => array('title' => $data['adPhotoTitle'], 'description'=>$data['adPhotoDescription'])), false, array('title', 'description','modified_by'));
      if (!empty($updateResult)) {
        $result = array('success' => true, 'data' => $updateResult, 'id' => $data['adPhotoId']);
      } else {
        $result = array('success' => false, 'message' => 'The record was not successfully update. Please try again.');
      }
    }
    $json = array('result' => $result);
    $this->set('json', $json);
    $this->render('/Elements/json', '/json/default');
  }

  private function _processAction($dataIn, $action='add', $id=null) {
    $this->layout = 'admin';
    $data = $this->_processRequestData($dataIn);
    $data["AdPhoto"]["image_path"] = $data["AdPhoto"]["photo_image_path"];
    $data["AdPhoto"]["title"] = $data["AdPhoto"]["photo_title"];
    $data["AdPhoto"]["description"] = $data["AdPhoto"]["photo_description"];
    $data["AdPhoto"]["single_photo"] = $data["AdPhoto"]["photo_single_photo"];
    $data["AdPhoto"]["ad_id"] = $data["AdPhoto"]["photo_ad_id"];
    if ($action === "add") {
      $this->AdPhoto->set($data);
      if ($this->AdPhoto->validates()) {
        if (!empty($data["AdPhoto"]["image_path"]) && !empty($data["AdPhoto"]["image_path"]['name'])) {
          $albumsFolder = Configure::read('App.adsImageFolder');
          $fileName = $this->Util->cleanFileName($data["AdPhoto"]["image_path"]['name'], true) . "_" . date("U");
          $imageWidth = $data["AdPhoto"]["single_photo"]==="Y" ? "" : Configure::read("App.adsImageWidth");
          $imageHeight = $data["AdPhoto"]["single_photo"]==="Y" ? "" : Configure::read("App.adsImageHeight");
          $thumbnailWidth = $data["AdPhoto"]["single_photo"]==="Y" ? Configure::read('App.adsLargeImageWidth') : Configure::read('App.photoImageThumbWidth');
          $imageUploaded = $this->Upload->uploadImage($data["AdPhoto"]["image_path"], WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $albumsFolder, $imageWidth, $imageHeight, $fileName,  true, $thumbnailWidth );
          $data["AdPhoto"]["image_path"] = $albumsFolder . '/' . $imageUploaded;
          $data["AdPhoto"]["image_thumb_path"] = $albumsFolder . '/' . Configure::read('App.defaultThumbnailPrefix') . $imageUploaded;
        }
        if ($this->AdPhoto->save($data, false)) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index', 'admin' => true, $data["AdPhoto"]["ad_id"]));
        }
      } else {
        $this->request->data['AdPhoto'] = $data['AdPhoto'];
        $this->set('errors', $this->Photo->validationErrors);
        $this->render('admin_add');
      }
    } elseif ($action === "edit") {
      $originalRec = $this->AdPhoto->find("first", array("conditions" => array("AdPhoto.id" => $id)));
      $this->AdPhoto->set($data);
      if ($this->AdPhoto->validates()) {
        //update record
        if ($this->AdPhoto->save($data, false, array('title','description'))) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index', 'admin' => true, $originalRec["AdPhoto"]["ad_id"]));
        }
      } else {
        $data['AdPhoto']['image_path'] = $originalRec["AdPhoto"]["image_path"];
        $data['AdPhoto']['id'] = $id;
        $this->request->data['AdPhoto'] = $data['AdPhoto'];
        $this->set('errors', $this->AdPhoto->validationErrors);
        $this->render('admin_edit');
      }
    }
  }

  function admin_delete($id, $adId) {
    $this->layout = 'admin';
    $this->deleteImage($id);
    if ($this->AdPhoto->delete($id)) {
      $this->Session->setFlash('The photo has been deleted.');
      $this->redirect(array('action' => 'index', 'admin' => true, $adId));
    }
  }

  function deleteImage($id) {
    $this->layout = 'admin';
    //TODO - Images are not being deleted
    $retVal = false;
    $image = $this->AdPhoto->read(array('image_path','image_thumb_path'), $id);
    $imagePath = $image['AdPhoto']['image_path'];
    $imageThumbPath = $image['AdPhoto']['image_thumb_path'];
    if (!empty($imagePath)) {
      $result = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imagePath);
      $resultThumb = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imageThumbPath);
      $retVal = $result && $resultThumb;
    }
    return $retVal;
  }

  private function _getOptions($adId=null) {
    $options = array();
     ////http://book.cakephp.org/view/1047/Joining-tables --joins
    //Get category name and album name
    if(!empty($adId)){
      $options['conditions'] = array(
        'Ad.id' => $adId
      );
    }
    $options['fields']= array (
        'Ad.id', 'Ad.description', 'Ad.single_photo','Company.id', 'Company.name' //Use Category alias here
    );
    return $options;
  }

  function admin_invalid(){
  //Throw 404 Exception
    throw new NotFoundException('The url that was entered was not valid');
  }

}

?>
